/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sunrise.boundary;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

/**
 *
 * @author frank
 * @param <T>
 */
public class GenericManager<T> {
    @PersistenceContext
    EntityManager entityManager;

    @Inject
    Principal principal;
    
    protected Class<T> typeParameterClass;
    
    public void save(T entity) {
        entityManager.persist(entity);
    }
    
    public void update(T entity) {
        entityManager.merge(entity);
    }
    
    public List<T> findManyWithNamedQuery(String queryName, Map<String, Object> params) {
        List<T> result = new ArrayList<T>();
        
        try {
            TypedQuery<T> query = entityManager.createNamedQuery(queryName, typeParameterClass);
            for(String key: params.keySet()) {
                query.setParameter(key, params.get(key));
            }
            result = query.getResultList();
        } catch (Exception ex) {

        }
        
        return result; 
    }
    
    public T findOneWithNamedQuery(String queryName, Map<String, Object> params) {
        T result = null;
        
        try {
            TypedQuery<T> query = entityManager.createNamedQuery(queryName, typeParameterClass);
            for(String key: params.keySet()) {
                query.setParameter(key, params.get(key));
            }
            result = query.getSingleResult();
        } catch (Exception ex) {

        }
        
        return result;
    }
}
